import { Button, Col, Input, Pagination, Row } from 'antd';
import React, { useEffect, useMemo, useState } from 'react';

// 假设你已经创建了 MenuList 和 OrderDetails 组件
import { queryCategoryByPage } from '@/services/swagger/categoryController';
import { queryItemByPage } from '@/services/swagger/itemController';
import { MenuList } from './components/MenuList';
import { OrderDetails } from './components/OrderDetails';

interface Dish {
  id: number;
  name: string;
  price: number;
  isVegetarian?: boolean;
}

const App: React.FC = () => {
  const [categories, setCategories] = useState<API.Category[]>([]);
  const [selectedCategoryId, setSelectedCategoryId] = useState<number | null>(null);
  const [orderItems, setOrderItems] = useState<API.OrderDetailDTO[]>([]);
  const [pageSize, setPageSize] = useState<number>();
  const [currentPage, setCurrentPage] = useState(1);
  const [dishes, setDishes] = useState<any[]>([]);
  const [loading, setLoading] = useState<boolean>(true);
  const [total, setTotal] = useState<number>(0);

  // 构建 dishId -> Dish 的映射表
  const dishMap = useMemo(() => {
    const map: Record<number, Dish> = {};
    dishes.forEach((dish) => {
      map[dish.id] = dish;
    });
    return map;
  }, [dishes]);

  // 将 fetchData 从 useEffect 中提取出来，作为组件内可复用函数
  const fetchData = async (
    params: { key?: string; category?: number; pageNo?: number; pageSize?: number } = {},
  ) => {
    setLoading(true);
    const { key, category, pageNo = currentPage, pageSize } = params;
    const response = await queryItemByPage({
      pageNo,
      pageSize,
      category,
      key,
    });
    if (response) {
      setDishes(response.list || []);
      setTotal(response.total || 0);
    }
    setLoading(false);
  };

  useEffect(() => {
    fetchData({ pageNo: currentPage, pageSize });
  }, [currentPage, pageSize]);

  useEffect(() => {
    const fetchCategories = async () => {
      try {
        const response = await queryCategoryByPage({
          pageNo: 1,
          pageSize: 10,
        });

        if (response) {
          setCategories(response.list || []);
        }
      } catch (error) {
        console.error('获取分类失败', error);
      }
    };

    fetchCategories();
  }, []);

  const handlePageChange = (page: number, size: number) => {
    setCurrentPage(page);
    setPageSize(size);
  };

  // 添加菜品到订单
  const addToOrder = (dish: Dish) => {
    const existingItem = orderItems.find((item) => item.itemId === dish.id);
    if (existingItem) {
      setOrderItems(
        orderItems.map((item) =>
          item.itemId === dish.id ? { ...item, num: (item.num || 0) + 1 } : item,
        ),
      );
    } else {
      setOrderItems([...orderItems, { itemId: dish.id, num: 1 }]);
    }
  };
  // 更新订单中某个菜品的数量
  const updateOrderQuantity = (itemId: number, delta: number) => {
    setOrderItems((prev) =>
      prev
        .map((item) =>
          item.itemId === itemId ? { ...item, num: Math.max(0, (item.num || 0) + delta) } : item,
        )
        .filter((item) => (item.num ?? 0) > 0),
    );
  };

  return (
    <Row gutter={16}>
      {/* 左侧：菜品展示区域 */}
      <Col span={16}>
        {/* 搜索栏 */}
        <div style={{ marginBottom: 16 }}>
          <Input.Search
            placeholder="输入菜品名称"
            onSearch={(value) => fetchData({ key: value })}
            style={{ width: '70%', margin: '0 auto' }}
          />
        </div>
        {/* “全部”按钮 */}
        <Button
          type={!selectedCategoryId ? 'primary' : 'default'}
          onClick={() => {
            setSelectedCategoryId(null);
            fetchData({});
          }}
          style={{ marginRight: 8, marginBottom: 8 }}
        >
          全部
        </Button>
        {/* 分类按钮列表 */}
        {categories.map((category) => (
          <Button
            key={category.id}
            type={selectedCategoryId === category.id ? 'primary' : 'default'}
            onClick={() => {
              console.log('点击了分类:', category.id);
              // @ts-ignore
              setSelectedCategoryId(category.id);
              fetchData({ category: category.id });
            }}
            style={{ marginRight: 8, marginBottom: 8 }}
          >
            {category.name}
          </Button>
        ))}

        {/* 菜品卡片列表 + 滚动容器 */}
        <div style={{ height: '600px', overflowY: 'auto', overflowX: 'hidden' }}>
          <MenuList dishes={dishes} loading={loading} onAddToOrder={addToOrder} />
        </div>
        <>
          <Pagination
            current={currentPage}
            pageSize={pageSize}
            total={total}
            onChange={handlePageChange}
            onShowSizeChange={handlePageChange}
            showSizeChanger
            align="center"
            style={{ marginTop: 12 }}
          />
        </>
      </Col>

      {/* 右侧：订单详情区域 */}
      <Col span={8}>
        <OrderDetails
          orderItems={orderItems}
          onUpdateQuantity={updateOrderQuantity}
          setOrderItems={setOrderItems}
          dishMap={dishMap} // 👈 新增 prop：传入 dishMap
        />
      </Col>
    </Row>
  );
};

export default App;
